package org.sfx.animation

import org.sfx.rich.Enrich._
import javafx.animation.KeyFrame
import javafx.animation.Timeline
import javafx.beans.property.SimpleDoubleProperty
import javafx.util.Duration
import javafx.animation.KeyValue
import javafx.beans.value.WritableValue
import javafx.event.EventHandler
import javafx.event.ActionEvent

class SfxTimeline() {
  val underlying = new Timeline()
  val terminatingDuration = Duration.ZERO
  
  def addTransition(duration: Duration)(f: Double => Unit): Unit = {
    val newTerminatingDuration = this.terminatingDuration.add(duration)
    val transitionProperty = new SimpleDoubleProperty(0.0)
    transitionProperty.addChangeListener { (_, _, newValue) => f(newValue.doubleValue()) }
    this.underlying.getKeyFrames().add(
        new KeyFrame(duration, new KeyValue(transitionProperty, new java.lang.Double(1.0))))
  }
  
  def addEvent(duration: Duration)(f: => Unit): Unit = {
    this.underlying.getKeyFrames().add(
        new KeyFrame(
            duration,
            new EventHandler[ActionEvent]() {
              override def handle(event: ActionEvent): Unit = f
            }))
  }
  
  def onFinished(f: => Unit): Unit = {
    underlying.setOnFinished(
        new EventHandler[ActionEvent]() {
          override def handle(event: ActionEvent): Unit = f
        })
  }
  
  def jumpTo(duration: Duration) = underlying.jumpTo(duration)
  
  def jumpTo(cuePoint: String) = underlying.jumpTo(cuePoint)
  
  def play(): Unit = underlying.play()
}
